package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private DataSource dataSource;

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        //配置数据源
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        // 注解标记允许匿名访问的url
//        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
//        permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
//        httpSecurity
//                .formLogin().loginProcessingUrl("/login");
                // CSRF禁用，因为不使用session
//                .csrf().disable()
                // 禁用HTTP响应标头
//                .headers().cacheControl().disable().and()
                // 认证失败处理类
//                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token，所以不需要session
//                .sessionManagement().maximumSessions(1).and().and();
                // 过滤请求
        httpSecurity
                .csrf().disable()
                .authorizeRequests()
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                .antMatchers(HttpMethod.POST,"/api/user/userLogin").permitAll()
//                .antMatchers(HttpMethod.GET, "/save_user", "/hello").permitAll()
                // 静态资源，可匿名访问
                .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
                .antMatchers("/api/approval/approvalEnd", "/api/purtc/purchaseDetail", "/api/coptc/selectCoptd").permitAll()
                .antMatchers("/api/mqtt/**","/files/**", "/api/websocket/**", "/api/system/sysMenu/toAssign/**").permitAll()
                .antMatchers("/api/flow/**","/api/purtb/report","/api/PurTl/report","/api/MocTm/report","/api/CopTa/report","/api/Invtl/report","/api/copte/report").permitAll()
                .antMatchers("/api/purtb/queryXq","/api/PurTl/queryXq","/api/CopTa/queryXq","/api/MocTm/queryXq","/api/Invtl/queryXq","/api/copte/queryXq").permitAll()
                .antMatchers("/api/Znx/**","/api/Cmsno/**","/api/Saas/**", "/api/sfcte/getExcel", "/api/pengChengReport/**","/api/cmsmq/getBuyListAll").permitAll()
                .antMatchers("/api/Kuchun/**","/api/invmb/invmabVoList","/api/invmb/selectInvmaHeadVoList","/api/Cmsni/getWarehouse","/api/cmsmc/selectCmsmcVo","/api/Cmsni/getWarehousestock").permitAll()
                .antMatchers("/api/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated().and().rememberMe().userDetailsService(userDetailsService).tokenRepository(tokenRepository);
//                .anyRequest().permitAll();
//                .and().httpBasic().and() .csrf().disable();
//                .and()
//                .headers().frameOptions().disable();
        //httpSecurity.formLogin().disable();
        // 添加Logout filter
//        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
        // 添加JWT filter
//        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
//        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
//        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
    }

//    @Bean
//    public MyAuthenticationProvider eacpsAuthenticationProvider() {
//        MyAuthenticationProvider myAuthenticationProvider = new MyAuthenticationProvider(userDetailsService);
////        myAuthenticationProvider.setUserDetailsService(userDetailsService);
//        return myAuthenticationProvider;
//    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
//        auth.authenticationProvider(new MyAuthenticationProvider(userDetailsService));
    }

    /**
     * 配置哪些请求不拦截
     * 排除swagger相关请求
//     * @param web
     * @throws Exception
     */
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers("/**","/diagram-viewer/**","/editor-app/**","/*.html",
//                "/admin/processImage/**",
//                "/admin/wechat/authorize","/admin/wechat/userInfo","/admin/wechat/bindPhone",
//                "/favicon.ico","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html");
//    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

}
